package cn.tedu.drawn.filter;

import cn.tedu.drawn.admin.pojo.vo.AdminVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//管理员页面未登录时的拦截器
@WebFilter(filterName = "AdminFilter",urlPatterns = {"/admin.html",
        "/insertProduct.html","/insertBanner.html"})
public class AdminFilter implements Filter {

    //在请求资源之前或之后会进入到此方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //判断是否登录
        HttpServletRequest rt = (HttpServletRequest) request;
        HttpServletResponse re = (HttpServletResponse) response;
        //禁止浏览器缓存所有动态页面
        re.setHeader("Pragma","no-cache");
        re.setHeader("Cache-Control","no-cache");
        re.setDateHeader("Expires", -1);
        //得到会话对象
        HttpSession session = rt.getSession();
        //从会话对象中得到登录的用户对象
        AdminVO user = (AdminVO) session.getAttribute("user");
        if (user!=null){//代表登录过 允许放行
            chain.doFilter(request, response);//放行
        }else{//没有登录 跳转到登录页面
            re.sendRedirect("/admin/login.html");//重定向到登录页面
        }
    }
}
